import axiosStatic, { AxiosInstance, AxiosRequestConfig } from '@ohos/axios'

const axios: AxiosInstance = axiosStatic.create({
  timeout: 20000,
  headers: { 'Content-Type': 'application/json' },
})
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 请求 拦截器
axios.interceptors.request.use((config) => {
  // let accessToken = 'tj7Mus4XNxzzTT_uA'
  // if (accessToken) {
  //     config.headers.Authorization = 'Bearer ' + accessToken
  // }
  return config
}, (error) => {
  // Do something with request error
  return Promise.reject(error)
});
//响应拦截器
axios.interceptors.response.use(
  (response) => {
    const resData = response.data
    // 未设置状态码则默认成功状态
    const code = resData.status || 200;
    const msg = resData.message
    // 二进制数据则直接返回
    if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
      return resData
    }
    if (code !== 200 && code != 0) {
      // if (msg) {
      //   ElMessage({
      //     message: msg,
      //     type: 'error'
      //   })
      // }
      if (code === 401) {
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
      } else if (code == 500) {
        // ElMessage({ message: msg, type: 'error' })
        return Promise.reject(new Error(msg))
      }
      return Promise.reject('error')
    } else {
      return Promise.resolve(resData);
    }
  },
  (error) => {
    // ElMessage.closeAll()
    console.log('err', error)
    if (error.response) {
      // if (error.response.status == 404) {
      //   showErrMsg("status:404,请求的资源不存在！");
      // } else if (error.response.status == 500) {
      //   showErrMsg(error.response.data.message || "status:500,服务器发生错误！");
      // } else if (error.response.status == 401) {
      //   showErrMsg(error.response.data.message || "status:401,服务器发生错误！");
      // } else {
      //   showErrMsg(error.message || `status:${error.response.status},未知错误！`);
      // }
    } else if (error.code == 'ERR_CANCELED') {
      //取消了
    } else {
      // showErrMsg(error.message || '请求服务器无响应！');
    }
    // 请求错误时做些事
    return Promise.reject(error)
  }
)


export const request = <TresponseData>(config: AxiosRequestConfig): Promise<TresponseData> => {
  return axios(config)
}

export default axios